//
//  HMTabBar.swift
//  Faner_Weibo
//
//  Created by 范英强 on 16/1/21.
//  Copyright © 2016年 范英强. All rights reserved.
//

import UIKit

class HMTabBar: UITabBar {
    //定义闭包变量
    var composeButtonClosure: (()->())?

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        //调整子控件的位置
        composeButton.center = CGPoint(x: frame.width * 0.5, y: frame.height * 0.5)
        //调整其他其他四个按钮
        let childW = frame.width / 5
        
        //自己维护一个当前遍历到的UITabBarButton
        var index: CGFloat = 0
        
        for value in subviews {
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!){
                
                let x = index * childW
                
                value.frame = CGRect(x: x, y: 0, width: childW, height: frame.height)
                
                index++
                
                if index == 2 {
                    index++
                }
                
                
            }
        }
    }
    
    // MARK: - 添加控件
    private func setupUI(){
        backgroundImage = UIImage(named: "tabbar_background")
        addSubview(composeButton)
        
    }
    
    // MARK: - 监听事件
    
    @objc private func composeButtonClick(){
        composeButtonClosure?()
    }
    
    
    
    
    // MARK: - 懒加载控件
    
    lazy var composeButton: UIButton = {
        let button = UIButton()
        //添加点击时间
        button.addTarget(self, action: "composeButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        //button 自适应
        button.sizeToFit()
        return button
    }()

}
